package com.fingard.dsp.bank.directbank.chinapay05;


import chinapay.PrivateKey;
import chinapay.SecureLink;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.text.StringHelper;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.NameValuePair;

import java.math.BigDecimal;
import java.util.Map;



public class ChinaPay05SinglePay extends ChinaPay05Base implements ISinglePay {

    /**
     * 单笔支付提交
     *
     * @param p_req1908
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail tmpRetDetail;
        tmpRetDetail = d_190802(p_req1908);
        if(tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)){
            tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    private RetAtsSglDetail d_190802(ReqSingle p_req1908) {
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req1908.singleDetail.payAct, "singlePay");
            if (actItem == null) {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = "未找到账号[" + p_req1908.singleDetail.payAct + "]商户配置信息!";
                return tmpRetDetail;
            }
            String merId = actItem.merchantId;
            String merDate = Format.Date8Format.format(Format.Date10Format.parse(p_req1908.singleDetail.payDate));
            String merSeqId = p_req1908.singleDetail.askNumber;
            String cardNo = p_req1908.singleDetail.recAct;
            String usrName = p_req1908.singleDetail.recName;
            String openBank = p_req1908.singleDetail.recBankName;
            String[] tmpRecAreaName = p_req1908.singleDetail.recAreaName != null ? p_req1908.singleDetail.recAreaName.split("_") : new String[]{""};
            String prov = tmpRecAreaName[0];
            String city = tmpRecAreaName[1];
            String transAmt = StringHelper.amountMultiply100(p_req1908.singleDetail.payAmount);
            String purpose =p_req1908.singleDetail.purpose;
            String subBank = "";
            String flag = "";  //1 对私 2对公   银行00 对私 01 对公
            if ("1".equals(p_req1908.singleDetail.isPrivate)) {
                flag = "00";
            } else {
                flag = "01";
            }
            String url= "";
            String msg = "";
            String version = getBankConfig().getValueAsString("singlePayVersion");
            if("20160530".equals(version)){
                subBank = p_req1908.singleDetail.cnapsName;//+"|"+ p_req1908.singleDetail.cnapsCode;
                msg = merId+merDate+merSeqId+cardNo+usrName+openBank+prov+city+transAmt+purpose
                        +subBank+flag+version+"07"+"1";
                url = bankFront.getUrl("singlePay1");
            }else if("20090501".equals(version)){
                subBank = p_req1908.singleDetail.cnapsName;
                msg = merId + merDate + merSeqId + cardNo + usrName + openBank + prov + city + transAmt + purpose + subBank + flag + version ;
                url = bankFront.getUrl("singlePay2");
            }else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = "未识别的singlePayVersion";
                return tmpRetDetail;
            }

            WriteBankLogLn("待签名的数据:" + msg);
            String chkValue = sign(msg,merId,actItem.ownKeyStorePath);
            WriteBankLogLn("签名后的chkValue:" + chkValue);
            //填入各个表单域的值
            NameValuePair[] data = {
                    new NameValuePair("merId", merId),
                    new NameValuePair("merDate", merDate),
                    new NameValuePair("merSeqId", merSeqId),
                    new NameValuePair("cardNo", cardNo),
                    new NameValuePair("usrName", usrName),
                    new NameValuePair("openBank", openBank),
                    new NameValuePair("prov", prov),
                    new NameValuePair("city", city),
                    new NameValuePair("transAmt", transAmt),
                    new NameValuePair("purpose", purpose),
                    new NameValuePair("subBank",subBank),
                    new NameValuePair("flag", flag),
                    new NameValuePair("version", version),
                    new NameValuePair("chkValue",chkValue),
                    new NameValuePair("termType","07"),
                    new NameValuePair("payMode","1"),
                    new NameValuePair("signFlag", "1")
            };
            String reqStr = "merId=" + merId + "&merDate=" + merDate + "&merSeqId=" + merSeqId + "&cardNo=" + cardNo + "&usrName=" + usrName + "&openBank=" + openBank + "&prov=" + prov + "&city=" + city + "&transAmt=" + transAmt + "&purpose=" + purpose + "&subBank=" + subBank + "&flag=" + flag + "&version=" + version + "&chkValue=" + chkValue + "&signFlag=1" + "&termType=07";
            WriteBankLogLn("发送银行的数据:" + reqStr);
            WriteBankLogLn("提交地址:" + url);
            String result = sendBatch(data,url,"singlePay");
            Map<String,String> resultMap = convertToMap(result);
            String tmpRespCode = "-1";

            String stat = resultMap.get("stat");
            String responseCode = resultMap.get("responseCode");
            String reqSeqID = resultMap.get("merSeqId");
            //如果stat为2.表示请求成功 其他为失败
            if ("0000".equals(responseCode)||"0103".equals(responseCode)||"0104".equals(responseCode)) {
                tmpRespCode = "0";
                tmpRetDetail.respCode = tmpRespCode;
                tmpRetDetail.respInfo = "";
                tmpRetDetail.transState =responseCode+"+"+ stat;
                tmpRetDetail.payInfoCode = responseCode+"+"+ stat;
                tmpRetDetail.reqSeqID = reqSeqID;
            } else {
                tmpRetDetail.respCode = tmpRespCode;
                tmpRetDetail.respInfo = "请求失败";
                tmpRetDetail.transState =responseCode;
                tmpRetDetail.payInfoCode = responseCode;
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        return tmpRetDetail;
    }

    /**
     * 单笔支付状态查询
     *
     * @param p_req1944
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
        tmpRetDetail.reqSeqID = p_req1944.askNumber;
        try{
            ActSetItem actItem = getBankConfig().getActSetItem(p_req1944.payAct, "singlePay");
            if (actItem == null) {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = "未找到账号[" + p_req1944.payAct + "]商户配置信息!";
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            String merId = actItem.merchantId;
            String merDate = Format.Date8Format.format(Format.Date10Format.parse(p_req1944.bgnDate));
            String merSeqId = p_req1944.askNumber;
            String url= "";
            String version = getBankConfig().getValueAsString("singlePayVersion");
            if("20160530".equals(version)){
                url = bankFront.getUrl("singlePayQuery1");
            }else if("20090501".equals(version)){
                url = bankFront.getUrl("singlePayQuery2");
            }else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = "未识别的singlePayVersion";
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            String msg = merId+merDate+merSeqId+version;
            WriteBankLogLn("待签名的数据:" + msg);
            String chkValue = sign(msg,merId,actItem.ownKeyStorePath);
            WriteBankLogLn("签名后的chkValue:" + chkValue);
            //填入各个表单域的值
            NameValuePair[] data = {
                    new NameValuePair("merId", merId),
                    new NameValuePair("merDate", merDate),
                    new NameValuePair("merSeqId", merSeqId),
                    new NameValuePair("version", version),
                    new NameValuePair("chkValue",chkValue),
                    new NameValuePair("signFlag", "1")
            };
            String reqStr = "merId=" + merId + "&merDate=" + merDate + "&merSeqId=" + merSeqId + "&version=" + version + "&chkValue=" + chkValue + "&signFlag=1";
            WriteBankLogLn("发送银行的数据:" + reqStr);
            WriteBankLogLn("提交地址:" + url);
            String result = sendBatch(data,url,"singlePay");
            String[] str = result.split("\\|");
            String tmpRespCode = "-1";

            String stat = str[14];
            String responseCode = str[0];
            String reqSeqID = str[3];
            //如果stat为2.表示请求成功 其他为失败
            if ("000".equals(responseCode)||"001".equals(responseCode)) {
                tmpRespCode = "0";
                tmpRetDetail.respCode = tmpRespCode;
                tmpRetDetail.respInfo = "";
                tmpRetDetail.transState =responseCode+"+"+ stat;
                tmpRetDetail.payInfoCode = responseCode+"+"+ stat;
                tmpRetDetail.reqSeqID = reqSeqID;
            } else {
                tmpRetDetail.respCode = tmpRespCode;
                tmpRetDetail.respInfo = "请求失败";
                tmpRetDetail.transState =responseCode;
                tmpRetDetail.payInfoCode = responseCode;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    /**
     * 单笔合批支付提交
     *
     * @param p_req1908BAT
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    /**
     * 单笔合批支付状态查询
     *
     * @param p_req1944BAT
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }


}
